using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for ScreenReader
/// </summary>
public class ScreenReader
{
    ControlReader CR = new ControlReader();
    DynamicDisplayI DDI = new DynamicDisplayI();
    HDDatabase HDD = new HDDatabase();
    public string errormessage = "";
    /// <summary>
    /// Captures the data in the screen.
    /// Datas are stored in the dataset and returned to the calling object.
    /// Dataset format is based on page set structure.
    /// No of tables is equvalent to the no. of the pages in the page set.
    /// Table name is page id of the page
    /// Column names are control ids in the page.
    /// </summary>
	public ScreenReader()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public DataSet CaptureData(string strPgsId, HtmlForm frmObj, DataSet dsePageInfo,bool isSaveMode)
    {
        HDDatabase HDD = new HDDatabase();
        string strPageId;
        string sAF_ROW_ID = "";
        DataSet dsePageData = new DataSet();
        DataTable dtaPageSet = dsePageInfo.Tables["PageSet"];
        DataTable dtaPage = dsePageInfo.Tables["Page"];
        DataTable dtaPageKeys = dsePageInfo.Tables["PageKeys"];
        DataTable dtaPageCtrl = dsePageInfo.Tables["PageCtrl"];
        DataTable dtaObjAtt = dsePageInfo.Tables["ObjectAttributes"];
        CreatePageDataTable(dsePageData, dtaPage, dtaPageCtrl);
        for (int i = 0; i < dtaPage.Rows.Count; i++)
        {
            strPageId = dtaPage.Rows[i]["page_id"].ToString();
            sAF_ROW_ID = dtaPage.Rows[i]["af_row_id"].ToString();
            //if (Convert.ToBoolean(HDD.getObjectRightsForUser(dtaPage.Rows[i]["object_id"].ToString())["edit"]))
                CapturePageData(dtaPage.Rows[i], frmObj, dtaPageCtrl.Select("page_id='" + sAF_ROW_ID + "'"), dsePageData,
                    dtaPage, dtaPageKeys, dtaPageCtrl,i,dtaObjAtt);
        }
        setDefaultValues(ref dsePageData,isSaveMode);
        //setMasterDetailRowID(ref dsePageData, ref dtaPage, ref dtaPageKeys);
        return dsePageData;
    }

    private string getMasterPageName(string Object_Id)
    {
        string sSQL = "Select master_obj from sy_obj_mas_detail mas_det inner join sy_obj obj on obj.af_row_id = mas_det.object_id where obj.object_id='" + Object_Id + "'";
        string sMaster = HDD.GetColumnValue(sSQL);
        return sMaster;
    }

    private void setMasterDetailRowID(ref DataSet PageData,ref DataTable PageInfo, ref DataTable PageKey)
    {
        foreach (DataTable dt in PageData.Tables)
        {
            string sPage_af_row_id = PageInfo.Select("page_id='" + dt.TableName + "'")[0]["af_row_id"].ToString();

            string sPage_Key = PageKey.Select("page_id='" + sPage_af_row_id +"'")[0]["page_key"].ToString();

            if (sPage_Key.ToLower() != "af_row_id")
            {
                string sMaster_af_row_id = "";
                string sMasterPage = PageInfo.Select("object_id='" + getMasterPageName(PageInfo.Select("page_id='" + dt.TableName + "'")[0]["object_id"].ToString()) + "'")[0]["page_id"].ToString();
                sMaster_af_row_id = PageData.Tables[sMasterPage].Rows[0]["af_row_id"].ToString();

                foreach (DataRow dr in dt.Rows)
                    dr[sPage_Key] = sMaster_af_row_id;
            }
        }
    }

    private void setDefaultValues(ref DataSet inputInfo, bool saveMode)//created by sanal on 13 Dec 2007
    {
        //string ss = HttpContext.Current.Session["userid"].ToString().Replace("'", "''");

        bool isCopymode = false;
        if (HttpContext.Current.Request.QueryString["CPY"] != null)
            isCopymode = true;

        string hashKey = "";
        try
        {
            foreach (DataTable dt in inputInfo.Tables)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        switch (dc.ColumnName.ToLower())
                        {
                            case "af_row_id":
                                //if (dr[dc.ColumnName].ToString() == "" || saveMode) // commented by srivatsan
                                if (dr[dc.ColumnName].ToString() == "" || isCopymode)
                                {
                                    hashKey = getHashKey();//if (hashKey == "")
                                    dr[dc.ColumnName] = hashKey;
                                }
                                break;
                            case "created_by":
                                if (dr[dc.ColumnName].ToString() == "" || saveMode)
                                {
                                    //if (sysVar.ContainsKey("Current User"))
                                    //    dr[dc.ColumnName] = sysVar["Current User"].ToString();
                                    //dr[dc.ColumnName] = HttpContext.Current.Session["userid"].ToString();
                                    dr[dc.ColumnName] = HttpContext.Current.Session["user_afrowid"].ToString();
                                }
                                break;
                            case "modified_at":
                                dr[dc.ColumnName] = DateTime.Now.ToUniversalTime().ToString(System.Globalization.CultureInfo.InvariantCulture);// System.DateTime.Now.ToUniversalTime().ToString();
                                break;
                            case "created_at":
                                if (dr[dc.ColumnName].ToString() == "" || saveMode)
                                    dr[dc.ColumnName] = DateTime.Now.ToUniversalTime().ToString(System.Globalization.CultureInfo.InvariantCulture); //System.DateTime.Now.ToUniversalTime().ToString();
                                //else
                                //{
                                //    if (dr[dc.ColumnName].ToString() != "")
                                //        dr[dc.ColumnName] = getUserFormat(dr[dc.ColumnName].ToString()).ToString(System.Globalization.CultureInfo.InvariantCulture); //System.DateTime.Now.ToUniversalTime().ToString();
                                //}
                                break;
                            case "modified_by":
                                //dr[dc.ColumnName] = HttpContext.Current.Session["userid"].ToString();
                                dr[dc.ColumnName] = HttpContext.Current.Session["user_afrowid"].ToString();
                                break;

                            case "owner_id": // Added by srivatsan on June 15 2009 for owner id field
                                //if (dr[dc.ColumnName].ToString() == "" || saveMode)
                                //{
                                //    if (dr[dc.ColumnName].ToString() == "")
                                //    {
                                //        if (!saveMode)
                                //        {
                                //            dr[dc.ColumnName] = dr["created_by"].ToString();
                                //        }
                                //        else
                                //        {
                                //            dr[dc.ColumnName] = HttpContext.Current.Session["user_afrowid"].ToString();
                                //        }
                                //    }
                                //}
                                break;



                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setDefaultValues. Error: " + e.Message);
        }
    }
    private DateTime getUserFormat(string input)
    {
        #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
        //Localization ll = new Localization();
        //DateTime rte = DateTime.Parse(input,ll.getUserCulture());
        //ll = null;
        #endregion
        DateTime rte = DateTime.Parse(input, MBLocale.MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString()));
        return rte;
    }
    private string getRandomString(int size, bool toUpperCase, ref Random random)
    {
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (toUpperCase)
            return builder.ToString().ToUpper();
        return builder.ToString();
    }
    private string GenerateId()
    {
        long i = 1;
        foreach (byte b in Guid.NewGuid().ToByteArray())
        {
            i *= ((int)b + 1);
        }
        return string.Format("{0:x}", i - DateTime.Now.Ticks);//converts to hexa decimal
    }
    public string getHashKey()
    {
        string temp = GenerateId();
        if (temp.Length != 16)
        {
            Random rnd = new Random();
            temp += getRandomString(16 - temp.Length, true, ref rnd);
            rnd = null;
        }
        return temp;
    }
    public bool CapturePageData(DataRow droPage, HtmlForm frmObj, DataRow[] droPageCtrl, DataSet dsePageData, 
        DataTable dtaPage, DataTable dtaPageKeys, DataTable dtaPageCtrl,int intPageSeq,DataTable dtaObjAtt)
    {
        bool blnStatus = true;
        string strCtrlId = "";
        string strCtrlValue = "";
        DataRow droPageData;
        string strPageId=droPage["page_id"].ToString();
        bool blnMultiplePage = Convert.ToBoolean(droPage["multiple_recs_page"].ToString());
        int intCurrentRow = 0;
        int intTotalRow = 1;
        if (blnMultiplePage)
        {
            HtmlInputHidden hihObj = (HtmlInputHidden)DDI.FindControl(frmObj.Controls, "_sys" + strPageId + "_RowCount");
            intTotalRow = Convert.ToInt32(hihObj.Value);

            // srivatsan for transaction document page
            if(HttpContext.Current.Request.Url.ToString().ToLower().Contains("transdoc.aspx"))
            {
            if (HttpContext.Current.Session["hfrowcount"] != null)
            {
                intTotalRow = Convert.ToInt32(HttpContext.Current.Session["hfrowcount"].ToString());
            }
            }
        }
        for (int j = 0; j < intTotalRow; j++)
        {
            intCurrentRow = j + 1;
            droPageData = dsePageData.Tables[strPageId].NewRow();
            for (int i = 0; i < droPageCtrl.Length; i++)
            {
                bool requiredfield = false; // Added by srivatsan to check required field
                security hdds = new security();
                if (!hdds.allRightsForNGMODEL())
                {
                    DataRow[] drr = dtaObjAtt.Select("attrib_id='" + droPageCtrl[i]["control_attrib_id"].ToString() + "'");
                    if (drr.Length > 0)
                    {
                        requiredfield = Convert2Bool(drr[0]["is_primary"].ToString());
                    }
                }
                


                /////strCtrlId = droPageCtrl[i]["control_id"].ToString();
                /////j
                strCtrlId = droPageCtrl[i]["control_attrib_id"].ToString();
                strCtrlValue = CR.CaptureCtrlData(droPageCtrl[i], dtaPage, dtaPageKeys, frmObj, dsePageData, dtaPageCtrl, intPageSeq, blnMultiplePage, intCurrentRow,requiredfield);
                droPageData[strCtrlId] = strCtrlValue;
                if (CR.errormessage != "")
                {
                    this.errormessage = CR.errormessage;
                    return false;
                }
            }
            dsePageData.Tables[strPageId].Rows.Add(droPageData);
        }

        return blnStatus;
    }
    private string EncodeData(string controlValue)
    {
        //return controlValue;
        try//uncommented as per the discussion by Sampath for IPP tech check.
        {
            return HttpContext.Current.Server.HtmlEncode(controlValue).ToString();
        }
        catch (Exception e)
        {
            return controlValue;
        }            
    }
    /// <summary>
    /// Creates the DataTable structure into the dsePageData dataset.
    /// dsePageData will be used to store the values in the screen.
    /// </summary
    /// <param name="dsePageData"></param>
    /// <param name="dtaPage"></param>
    /// <param name="dtaPageCtrl"></param>
    /// <returns></returns>
    public bool CreatePageDataTable(DataSet dsePageData, DataTable dtaPage, DataTable dtaPageCtrl)
    {
        bool blnStatus = true;
        DataRow droPage;
        DataTable dtaObj;
        DataRow[] droPageCtrl;
        DataColumn dtcObj;
        for (int i = 0; i < dtaPage.Rows.Count; i++)
        {
            droPage = dtaPage.Rows[i];
            dtaObj = new DataTable();
            dtaObj.TableName = droPage["page_id"].ToString();
            //droPageCtrl = dtaPageCtrl.Select("page_id='" + droPage["page_id"].ToString().Replace("'", "''") + "'");
            droPageCtrl = dtaPageCtrl.Select("page_id='" + droPage["af_row_id"].ToString() + "'");
            for (int j = 0; j < droPageCtrl.Length; j++)
            {
                dtcObj = new DataColumn();
                /////dtcObj.ColumnName = droPageCtrl[j]["control_id"].ToString();
                /////j
                dtcObj.ColumnName = droPageCtrl[j]["control_attrib_id"].ToString();
                // Datacolumn type needs to set. ColumnType = ControlDataType
                //For eg: dtcObj.DataType=droPagectrl[j]["control_data_type"];
                //dtcObj.DataType=System.Type.
                dtaObj.Columns.Add(dtcObj);
            }
            dsePageData.Tables.Add(dtaObj);
        }
        return blnStatus;
    }

    private bool Convert2Bool(string strdata)
    {
        bool result = false;
        try
        {
            if (strdata != "")
            {
                result = Convert.ToBoolean(strdata);
            }
        }
        catch(Exception ex)
        {

        }
        return result;

    }

}
